package com.aiyige.base.api.httpinterceptor;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.jpush.TagAliasOperatorHelper;
import com.aiyige.model.AiyigeExceptionModel;
import com.aiyige.model.response.BaseResponse;
import com.aiyige.page.my.message.util.MessageUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.crash.CrashUtils;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by zhuyakun on 2018/2/24.
 */

public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        if (response.code() == ResponseCode.UNAUTHORIZED) {
            try {
                String json = response.body().string();
                BaseResponse baseResponse = JsonUtil.toObject(json, BaseResponse.class);
                switch (baseResponse.getCode()) {
                    case ResponseCode.TOKEN_ERROR:
                    case ResponseCode.TOKEN_EXPIRED:
                    case ResponseCode.NOT_LOGIN:
                    case ResponseCode.LOGIN_FIRST: {
                        AccountUtil.clearCurrentUser();
                        MessageUtil.clearNewMessage();
                        TagAliasOperatorHelper.getInstance().cleanLoginTagAndAlias(MyApp.getAppContext());
                        ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
                        throw new Exception(StringUtils.getString(R.string.token_expired));
                    }
                    default: {
                        return response.newBuilder()
                                .body(ResponseBody.create(MediaType.parse("text/plain"), json))
                                .build();
                    }
                }
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        } else {
            return response;
        }
    }
}
